<template>
  <div class="app-container">
    <el-card shadow="never" class="mainCard" v-loading="loading">
      <div style="width: 100%; height: 40px;">
        <el-button type="warning" size="small" link style="float: right; margin-left: 10px;" @click="reback()">返
          回</el-button>
      </div>
      <div>
        <div style="margin-bottom: 10px;">
          <p><span>样本编号：</span><span>{{ checkedSample.number }}</span></p>
          <p style="margin-top: 8px;"><span>样本状态：</span><span>{{ checkedSample.statusText }}</span></p>
        </div>
        <el-tabs v-model="activeName" @tab-click="handleTabsClick">
          <el-tab-pane label="流程信息" name="first">
            <div style="height: 500px;">
              <el-steps direction="vertical" :active="activeStep">
                <el-step title="已创建" :description="sampleHistoryTimeMap['CREATE']"></el-step>
                <el-step title="待寄出" :description="sampleHistoryTimeMap['TO_BE_SENT_OUT']"></el-step>
                <el-step title="已寄出" :description="sampleHistoryTimeMap['SENT_OUT']"></el-step>
                <el-step title="样本已收到" :description="sampleHistoryTimeMap['SAMPLE_RECEIVE']"></el-step>
                <el-step title="测序完成" :description="sampleHistoryTimeMap['REPORT_SEQ_END']"></el-step>
                <el-step title="数据分析中" :description="sampleHistoryTimeMap['DATA_ANALYSIS']"></el-step>
                <el-step title="样本待审核" :description="sampleHistoryTimeMap['REPORT_AUDIT']"></el-step>
                <el-step title="已完成" :description="sampleHistoryTimeMap['COMPLETED']"></el-step>
              </el-steps>
            </div>
          </el-tab-pane>
          <el-tab-pane label="问卷信息" name="second">
            <el-form ref="survyFormRef" label-width="120px"
              :disabled="checkedSample.status != 'TO_BE_SENT_OUT' && checkedSample.status != 'SENT_OUT'">
              <div v-for="(data, index) in surveyObj.pageQuestions" :key="data.id"
                style="margin-top: 10px; padding-left: 2%; padding-right: 2%;">
                <label>
                  <span style="font-size: 16px;">{{ (index + 1) + '、' + data.title }}</span>
                  <span style="margin-left: 5px;">【{{ typeMap[data.type] }}】</span>
                </label>
                <div style="margin-top: 10px; padding-left: 2%; padding-right: 2%;">
                  <template v-if="data.type == 'EXCLUSIVE_CHOICE'">
                    <el-radio v-model="answerFormData[index].answer" v-for="(option) in data.options" :key="option.id"
                      :label="option.id">{{ option.title }}</el-radio>
                  </template>
                  <template v-if="data.type == 'MULTIPLE_CHOICE'">
                    <el-checkbox v-model="answerFormData[index].answer[j]" v-for="(option, j) in data.options"
                      :key="option.id">{{ option.title }}</el-checkbox>
                  </template>
                  <template v-if="data.type == 'TEXTAREA'">
                    <el-input v-model="answerFormData[index].answer" placeholder="请输入内容"></el-input>
                  </template>
                </div>
              </div>
            </el-form>
            <div style="margin-top: 10px; float: right;"
              v-if="(checkedSample.status == 'TO_BE_SENT_OUT' || checkedSample.status == 'SENT_OUT')">
              <el-button type="primary" @click="saveSurveyDialog">保 存</el-button>
            </div>
            <p v-if="checkedSample.status == 'CREATE'" style="text-align: center; margin-top: 10px;">暂无信息</p>
          </el-tab-pane>
          <el-tab-pane label="快递信息" name="third">
            <el-table v-loading="loading" :data="expressRouterList" highlight-current-row border>
              <el-table-column label="地址" prop="acceptAddress" />
              <el-table-column label="时间" prop="acceptTime" />
              <el-table-column label="备注" prop="remark" />
            </el-table>
          </el-tab-pane>
        </el-tabs>
      </div>
    </el-card>

  </div>
</template>

<script>
import sampleApi from '@/api/aliyun/detection/sample'
import surveyApi from '@/api/aliyun/questionnaire/survey'
import answerApi from '@/api/aliyun/questionnaire/answer'
import applicationApi from '@/api/system/application'
import sampleHistoryApi from '@/api/aliyun/detection/sample/history'
import { formatDate } from '@/utils/formatTime'
import expressApi from '@/api/aliyun/detection/express'

export default {
  name: 'sampleDetailDesign',
  props: {
    checkedSample: {
      type: Object,
      default: {},
    },
  },
  data() {
    return {
      loading: false,
      activeName: 'first',
      sampleHistoryTimeMap: {},
      activeStep: 0,

      answerFormData: [],
      surveyObj: {},
      optionTitleMap: {},
      typeMap: {
        EXCLUSIVE_CHOICE: '单选',
        MULTIPLE_CHOICE: '多选',
        TEXTAREA: '填空',
      },

      expressRouterList: [],
    }
  },
  mounted() {
    this.init();
  },
  methods: {
    init() {
      switch (this.activeName) {
        case 'first':
          this.sampleHistoryList()
          break;
        case 'second':
          this.sampleSurveyInfo()
          break;
        case 'third':
          this.sampleExpressInfo()
          break;
      }
    },
    sampleExpressInfo() {
      if (this.checkedSample.status == 'CREATE' || this.checkedSample.status == 'TO_BE_SENT_OUT') {
        return;
      }
      this.loading = true;
      expressApi.routersSample(this.checkedSample.id).then(res => {
        this.expressRouterList = res.data.routeDtos;
        this.loading = false;
      }).catch(() => { this.loading = false; });
    },
    saveSurveyDialog() {
      let answerJsonArr = [];
      let index = 0;
      this.surveyObj.pageQuestions.forEach(v => {
        let type = v.type;
        let answer = {};
        if (type === 'EXCLUSIVE_CHOICE') {
          answer = {
            id: this.answerFormData[index].answer,
            title: this.optionTitleMap[v.id + '-' + this.answerFormData[index].answer].optionTitle
          }
        } else if (type === 'MULTIPLE_CHOICE') {
          answer = [];
          for (let i = 0, len = this.answerFormData[index].answer.length; i < len; i++) {
            if (this.answerFormData[index].answer[i]) {
              answer.push({
                id: v.options[i].id,
                title: v.options[i].title
              });
            }
          }
        } else {
          answer = this.answerFormData[index].answer;
        }
        answerJsonArr.push({
          id: v.id,
          title: v.title,
          type: v.type,
          answer: answer
        })
        index++;
      })
      answerApi.add({
        id: this.answerId,
        surveyId: this.surveyObj.id,
        sampleId: this.checkedSample.id,
        contentJson: JSON.stringify(answerJsonArr)
      }).then(res => {
        this.$message({ message: '样本问卷保存成功！', type: 'success' });
      })
    },
    sampleSurveyInfo() {
      if (this.checkedSample.status == 'CREATE') {
        return;
      }
      answerApi.getBySampleId(this.checkedSample.id).then(resp => {
        let contentJson = resp.data.contentJson;
        this.answerId = resp.data.id;
        let contentJsonMap = {};
        if (contentJson) {
          contentJson = JSON.parse(contentJson);
          contentJson.forEach(contentJsonV => {
            contentJsonMap[contentJsonV.id] = contentJsonV.answer;
          })
        }

        applicationApi.getType('MBIOLANCE_UI').then(res => {
          let extJson = res.data.extJson;
          let obj = JSON.parse(extJson);
          let surveyId = obj.surveyId;
          this.answerFormData = []
          surveyApi.detail(surveyId).then(r => {
            this.surveyObj = r.data

            r.data.pageQuestions.forEach(v2 => {
              let answer = null;
              if (v2.type === 'EXCLUSIVE_CHOICE') {
                if (contentJsonMap[v2.id]) {
                  answer = contentJsonMap[v2.id].id;
                } else {
                  answer = -1;
                }
              } else if (v2.type === 'MULTIPLE_CHOICE') {
                answer = [];
                if (contentJsonMap[v2.id]) {
                  let multiAnswerMap = {}
                  if (contentJsonMap[v2.id] && contentJsonMap[v2.id].length != 0) {
                    contentJsonMap[v2.id].forEach(multiAnswer => {
                      multiAnswerMap[multiAnswer.id] = true;
                    })
                    v2.options.forEach(mulV2Option => {
                      if (multiAnswerMap[mulV2Option.id]) {
                        answer.push(true);
                      } else {
                        answer.push(false)
                      }
                    })
                  }
                }
              } else {
                answer = contentJsonMap[v2.id] ? contentJsonMap[v2.id] : ''
              }
              this.answerFormData.push({
                answer: answer
              })
              if (v2.options) {
                v2.options.forEach(op => {
                  this.optionTitleMap[v2.id + '-' + op.id] = {
                    optionTitle: op.title
                  }
                })
              }
            })
          })
        })
      })
    },
    sampleHistoryList() {
      sampleHistoryApi.list(this.checkedSample.number).then(res => {
        let data = res.data;
        let sampleHistoryTimeMap = {};
        let activeStep = 0;
        data.forEach(v => {
          sampleHistoryTimeMap[v.status + ''] = formatDate(new Date(v.createTime), "YYYY-mm-dd HH:MM:SS")
          activeStep++;
        })
        this.sampleHistoryTimeMap = sampleHistoryTimeMap;
        this.activeStep = activeStep;
      })
    },
    handleTabsClick(tab, event) {
      console.log(tab, event);
      this.init()
    },
    reback() {
      this.$emit("close");
    },
  }
}
</script>